<template>
  <div class="main-container">
    <div class="tables">
      <div class="tables1" style="width: 70%">
        <div class="box">
          <div class="text" style="display: flex; align-items: center"
            ><img
              style="width: 20px; height: 20px; margin-right: 10px"
              src="@/assets/qianqian.png"
              alt=""
            />
            系统余额：{{ balance }}元<span
              style="margin-left: 15px; color: #3491fa; cursor: pointer"
              @click="openBalance"
              >充值余额</span
            >
          </div>
        </div>
        <a-alert :show-icon="false" style="margin-bottom: 10px; background-color: #e8f7ff">
          <span style="color: #3491fa">
            短信/应用/服务费/分期款/手续费/订单费，都可以使用系统余额进行支付，其中：服务费/分期款/手续费/订单费都会在出账后，自动扣除系统余额，请保证余额充足以免影响使用</span
          >
        </a-alert>
        <a-modal
          v-model:visible="visibleBalance"
          @cancel="closeBalance"
          title="充值余额"
          width="456px"
          :mask-closable="false"
          title-align="start"
        >
          <a-alert :show-icon="false" style="margin-bottom: 20px; background-color: #e8f7ff">
            <span style="color: #3491fa; font-size: 12px">
              充值的余额可用于自动扣费和购买短信应用，请按需充值余额！</span
            >
          </a-alert>
          <a-form ref="balanceRef" :auto-label-width="false" :model="balanceForm">
            <a-form-item
              hide-label
              field="account"
              :rules="[{ required: true, message: '充值金额不能为空' }]"
              :validate-trigger="['change', 'input']"
            >
              <a-input
                v-model.trim="balanceForm.account"
                placeholder="请输入充值金额"
                allow-clear
              />
            </a-form-item>
            <a-form-item hide-label field="feeDetails">
              <div class="banList">
                <div
                  @click="radioBalance(item)"
                  v-for="(item, index) in balanceList"
                  :key="index"
                  class="box-ban"
                  >{{ item.balance }}元</div
                >
              </div>
            </a-form-item>
            <a-form-item field="payType" hide-label>
              <a-radio-group
                class="radio-bcg"
                @change="getPayListFns"
                v-model="subForm.payForms.payType"
              >
                <a-radio v-for="(item, index) in subForm.payForms.list" :key="index" :value="index">
                  <template #radio="{ checked }">
                    <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                      <div className="custom-radio-card-mask">
                        <div className="custom-radio-card-mask-dot"></div> </div
                      ><div className="custom-radio-card-title">{{ item.payType.name }}</div>
                    </div>
                  </template>
                </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item field="post" v-if="subForm.payForms.payList > 1" hide-label>
              <a-select
                placeholder="请选择支付商户"
                allow-search
                v-model="balanceForm.payId"
                allow-clear
              >
                <a-option
                  v-for="item in subForm.payForms.payList"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-form>
          <template #footer>
            <a-space>
              <a-button @click="closeBalance">取消</a-button>
              <a-button type="primary" @click="balanceOk">确定</a-button>
            </a-space>
          </template>
        </a-modal>
        <div class="box">
          <div class="line"></div>
          <div class="text"
            >系统费用<span v-if="dataList1.length > 0" class="redText"
              >当前手续费、订单费，已到期，请进行金额缴纳</span
            >
            <span v-else class="redText" style="color: forestgreen">已缴纳</span>
          </div>
        </div>
        <a-table :data="dataList1" :pagination="false">
          <template #columns>
            <a-table-column
              v-for="item of columns"
              :key="item.key"
              align="left"
              :title="(item.title as string)"
              :width="item.width"
              :data-index="(item.key as string)"
            >
              <template v-if="item.key === 'actions'" #cell="{ record }">
                <a-space>
                  <a-button size="small" type="text" class="butten" @click="xtjiaona(record)">
                    立即缴纳
                  </a-button>
                </a-space>
              </template>

              <template v-else-if="item.key === 'orderType'" #cell="{ record }">
                <span
                  v-for="(item, index) in list.list"
                  :key="index"
                  v-show="item.type == record.orderType"
                >
                  {{ item.name }}
                </span>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
      <div class="tables2" style="width: 100%; margin-top: 30px">
        <div class="box">
          <div class="line"></div>
          <div class="text">
            <a-radio-group v-model="activeType" type="button" @change="changeList">
              <a-radio value="0">服务费</a-radio>
              <a-radio value="1">分期款</a-radio>
              <a-radio value="2">手续费</a-radio>
              <a-radio value="3">订单费</a-radio>
            </a-radio-group></div
          >
        </div>
        <TableBody>
          <a-table :data="table.dataList" :pagination="false">
            <template #columns>
              <a-table-column
                v-for="item of columnsUse"
                :key="item.key"
                align="left"
                :title="(item.title as string)"
                :width="item.width"
                :data-index="(item.key as string)"
              >
                <template v-if="item.key === 'startTime'" #cell="{ record }">
                  <span>
                    {{ record.startTime + '-' + record.endTime }}
                  </span>
                </template>
                <template v-else-if="item.key === 'paymentType'" #cell="{ record }">
                  <span
                    v-for="(item, index) in list.payList"
                    :key="index"
                    v-show="item.type == record.paymentType"
                  >
                    {{ item.name }}
                  </span>
                </template>
              </a-table-column>
            </template>
          </a-table>
          <template #footer>
            <TableFooter :pagination="pagination" />
          </template>
        </TableBody>
      </div>
    </div>
    <a-modal
      v-model:visible="visible"
      @cancel="handleCancel"
      title="金额缴纳"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="userForm" :auto-label-width="true" :model="subForm.form">
        <a-form-item
          label="费用名称"
          :readonly="true"
          :rules="[{ required: true, message: '费用名称不能为空' }]"
          :validate-trigger="['change', 'input']"
          field="orderType"
          disabled
          asterisk-position="end"
        >
          <a-select
            :readonly="true"
            v-model="subForm.form.orderType"
            placeholder="请选择费用名称"
            allow-clear
          >
            <a-option v-for="(item, index) in list.list" :key="index" :value="item.type">{{
              item.name
            }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="费用简介"
          field="feeDetails"
          :rules="[{ required: true, message: '费用简介不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input
            :readonly="true"
            v-model.trim="subForm.form.feeDetails"
            placeholder="请输入费用简介"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          label="缴纳期数"
          field="numberInstallments"
          v-if="subForm.form.orderType == 1"
          :rules="[{ required: true, message: '缴纳期数' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input-number
            v-model.trim="subForm.form.numberInstallments"
            placeholder="请输入缴纳期数"
            @change="changenum(subForm.form.numberInstallments)"
            hide-button
            allow-clear
          />
        </a-form-item>
        <a-form-item
          label="缴纳费用"
          :readonly="true"
          field="money"
          :rules="[{ required: true, message: '缴纳费用不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input
            :readonly="true"
            v-model.trim="subForm.form.money"
            placeholder="请输入缴纳费用"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          label="缴纳时段"
          field="times"
          :rules="[{ required: true, message: '缴纳时段不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input
            :readonly="true"
            v-model.trim="subForm.form.times"
            placeholder="请输入缴纳时段"
            allow-clear
          />
        </a-form-item>

        <a-form-item label="支付方式" field="payType">
          <a-radio-group @change="getPayListFn" v-model="subForm.payForms.payType">
            <a-radio v-for="(item, index) in subForm.payForms.list" :key="index" :value="index">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">{{ item.payType.name }}</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="post" v-if="subForm.payForms.payList > 1" label="支付商户">
          <a-select
            placeholder="请选择支付商户"
            allow-search
            v-model="subForm.form.payId"
            allow-clear
          >
            <a-option v-for="item in subForm.payForms.payList" :key="item.id" :value="item.id">{{
              item.name
            }}</a-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleBeforeOk">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <a-modal
      v-model:visible="visibles"
      title="扫码支付"
      width="280px"
      :mask-closable="false"
      title-align="start"
      hide-cancel
      hide-ok
    >
      <div
        ><div style="text-align: center"
          >￥<span style="font-size: 26px">{{
            balanceType.value == 2 ? subForm.form.money : balanceForm.account
          }}</span></div
        >
        <img style="width: 240px; height: 240px" :src="subForm.form.imgUrl" alt="" />
      </div>
      <template #footer>
        <a-space>
          <a-button type="primary" @click="paySuccessFn">我已支付</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { usePagination, useTable } from '@/hooks/table'
  import { Message } from '@arco-design/web-vue'
  import {
    qr,
    paySuccess,
    getFeeList,
    getOrderType,
    getPaytype,
    getService,
    getinstallment,
    gethandling,
    getorder,
    payList,
    pay,
    getDatePay,
    payBalance,
    news,
  } from '@/api/url'
  import * as http from '@/api/http'
  import { reactive } from 'vue'
  import { get } from '@/api/http'
  const pagination = usePagination(doRefresh)
  const table = useTable()
  const visible = ref(false)
  const visibles = ref(false)
  const userForm = ref()
  const visibleBalance = ref(false)
  const balanceRef = ref()
  const balanceType = ref(1)
  const balanceForm = ref({
    account: '',
    payId: '',
    payType: '',
  })
  const balanceList = ref([
    { id: 1, balance: 100 },
    { id: 2, balance: 200 },
    { id: 3, balance: 500 },
    { id: 4, balance: 1000 },
    { id: 5, balance: 2000 },
    { id: 6, balance: 3000 },
  ])
  const columns = [
    {
      title: '费用名称',
      dataIndex: 'orderType',
      key: 'orderType',
      ellipsis: true,
      tooltip: true,
      width: 100,
    },
    {
      title: '费用介绍',
      dataIndex: 'feeDetails',
      key: 'feeDetails',
      width: 200,
    },
    {
      title: '到期时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 190,
    },
    {
      title: '操作',
      key: 'actions',
      dataIndex: 'actions',
      width: 120,
      align: 'center',
    },
  ]
  const columnsUse: any = ref([])
  const columns2 = [
    {
      title: '商品名称',
      dataIndex: 'feeDetails',
      key: 'feeDetails',
      ellipsis: true,
      tooltip: true,
      width: 160,
    },
    {
      title: '支付类型',
      dataIndex: 'paymentType',
      key: 'paymentType',
      width: 120,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 80,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 80,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 190,
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      key: 'payTime',
      width: 190,
    },
    {
      title: '缴纳时间段',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 240,
    },
  ]
  const columns2_fenqi = [
    {
      title: '商品名称',
      dataIndex: 'feeDetails',
      key: 'feeDetails',
      ellipsis: true,
      tooltip: true,
      width: 160,
    },
    {
      title: '支付类型',
      dataIndex: 'paymentType',
      key: 'paymentType',
      width: 120,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 80,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 80,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 80,
    },
    {
      title: '期数',
      dataIndex: 'numberInstallments',
      key: 'numberInstallments',
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 190,
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      key: 'payTime',
      width: 190,
    },
    {
      title: '缴纳时间段',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 240,
    },
  ]
  const dataList1 = ref([])
  const activeType = ref('0')
  const tableLoading = ref(false)
  const list: any = reactive({
    list: [],
    payList: [],
  })
  const subForm: any = reactive({
    form: {
      orderType: '',
      feeDetails: '',
      numberInstallments: '',
      money: '',
      startTime: '',
      endTime: '',
      type: '',
      payId: 0,
      payList: [],
    },
    payForms: {
      list: [],
      payType: 0,
      payList: [],
    },
  })
  //打开余额充值
  function openBalance() {
    balanceType.value = 1
    payListFn()
    subForm.payForms.payList = subForm.payForms.list[0].paymentLists
    balanceForm.value.payId = subForm.payForms.list[0].paymentLists[0].id
    visibleBalance.value = true
  }
  //关闭余额充值
  function closeBalance() {
    balanceForm.value.account = ''
    balanceForm.value.payId = ''
    subForm.payForms.payType = 0
    visibleBalance.value = false
  }
  //选中固定余额
  function radioBalance(item: any) {
    balanceForm.value.account = item.balance
  }
  //确定充值余额
  function balanceOk() {
    balanceRef.value?.validate().then((error: any) => {
      if (!error) {
        http
          .get({
            url: payBalance,
            data: {
              payId: balanceForm.value.payId,
              amount: balanceForm.value.account,
            },
          })
          .then((res) => {
            if (res.code == 0) {
              subForm.form.payForm = res.data
              visibleBalance.value = false
              if (res.data.returnType == 3) {
                subForm.form.imgUrl = `${window.location.protocol}//${window.location.host}${qr}?content=${res.data.data}`
                visibles.value = true
              } else if (res.data.returnType == 2) {
                window.location.href = res.data.data
              } else if (res.data.returnType == 4) {
                Message.success('购买成功')
              }
            }
          })
          .catch(() => {})
      }
    })
  }

  const handleCancel = () => {
    subForm.form = {
      orderType: '',
      numberInstallments: '',
      feeDetails: '',
      money: '',
      startTime: '',
      endTime: '',
      type: '',
      payId: 0,
    }
    visible.value = false
  }
  const changenum = (e: any) => {
    http
      .get({
        url: getDatePay,
        data: () => {
          return { orderId: subForm.form.orderId, orderType: subForm.form.orderType, number: e }
        },
      })
      .then((res: any) => {
        subForm.form.times = res.data.startTime + '至' + res.data.endTime
        subForm.form.money = res.data.money
      })
      .catch(console.log)
  }
  const handleBeforeOk = () => {
    userForm.value?.validate().then((error: any) => {
      if (!error) {
        http
          .get({
            url: pay,
            data: {
              payId: subForm.form.payId,
              objectId: subForm.form.orderId,
              payType: subForm.form.orderType,
              number: subForm.form.numberInstallments,
            },
          })
          .then((res) => {
            if (res.code == 0) {
              subForm.form.payForm = res.data
              visible.value = false
              if (res.data.returnType == 3) {
                subForm.form.imgUrl = `${window.location.protocol}//${window.location.host}${qr}?content=${res.data.data}`
                visibles.value = true
              } else if (res.data.returnType == 2) {
                window.location.href = res.data.data
              } else if (res.data.returnType == 4) {
                Message.success('购买成功')
              }
            }
          })
          .catch(() => {})
      }
    })
  }
  const changeList = (e: any) => {
    if (e == '0') {
      columnsUse.value = columns2
      http
        .get({
          url: getService,
          data: () => {
            return { page: pagination.page, size: pagination.pageSize }
          },
        })
        .then((res: any) => {
          tableLoading.value = false
          table.handleSuccess(res.data.list)
        })
        .catch(console.log)
    } else if (e == '1') {
      columnsUse.value = columns2_fenqi
      http
        .get({
          url: getinstallment,
          data: () => {
            return { page: pagination.page, size: pagination.pageSize }
          },
        })
        .then((res: any) => {
          tableLoading.value = false
          table.handleSuccess(res.data.list)
        })
        .catch(console.log)
    } else if (e == '2') {
      columnsUse.value = columns2
      http
        .get({
          url: gethandling,
          data: () => {
            return { page: pagination.page, size: pagination.pageSize }
          },
        })
        .then((res: any) => {
          tableLoading.value = false
          table.handleSuccess(res.data.list)
        })
        .catch(console.log)
    } else if (e == '3') {
      columnsUse.value = columns2
      http
        .get({
          url: getorder,
          data: () => {
            return { page: pagination.page, size: pagination.pageSize }
          },
        })
        .then((res: any) => {
          tableLoading.value = false
          table.handleSuccess(res.data.list)
        })
        .catch(console.log)
    }
  }
  const xtjiaona = (record: any) => {
    balanceType.value = 2
    subForm.form.orderType = record.orderType
    subForm.form.feeDetails = record.feeDetails
    subForm.form.money = record.money
    subForm.form.startTime = record.startTime
    subForm.form.endTime = record.endTime
    subForm.form.orderId = record.id

    if (record.numberInstallments) subForm.form.numberInstallments = record.numberInstallments
    else subForm.form.numberInstallments = 0
    subForm.form.times = record.startTime + '至' + record.endTime
    console.log(subForm.payForms.list)
    subForm.payForms.payList = subForm.payForms.list[0].paymentLists
    subForm.form.payId = subForm.payForms.list[0].paymentLists[0].id
    visible.value = true
  }
  const getPayListFn = () => {
    subForm.payForms.payList = subForm.payForms.list[subForm.payForms.payType].paymentLists
    subForm.form.payId = subForm.payForms.list[subForm.payForms.payType].paymentLists[0].id
    console.log(subForm.form.payId)
  }
  const getPayListFns = () => {
    subForm.payForms.payList = subForm.payForms.list[subForm.payForms.payType].paymentLists
    balanceForm.value.payId = subForm.payForms.list[subForm.payForms.payType].paymentLists[0].id
  }
  function is_weixn() {
    var ua: any = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      subForm.form.type = 1
      return true
    } else {
      subForm.form.type = 2
      return false
    }
  }

  is_weixn()
  const payListFn = () => {
    http
      .get({
        url: payList,
        data: { type: subForm.form.type },
      })
      .then((res) => {
        subForm.payForms.list = res.data
        console.log(subForm.payForms.list)
      })
  }
  const paySuccessFn = () => {
    if (balanceType.value == 2) {
      http
        .get({
          url: paySuccess,
          data: {
            orderNumber: subForm.form.payForm.systemOrderNumber,
            type: subForm.form.payForm.orderType,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            visibles.value = false
            Message.success(res.msg)
            doRefresh()
          }
        })
        .catch(() => {})
    } else {
    }
  }
  function getTypeList() {
    http
      .get({
        url: getOrderType,
        data: () => {
          return {}
        },
      })
      .then((res: any) => {
        list.list = res.data
      })
  }
  function getpayTypeList() {
    http
      .get({
        url: getPaytype,
        data: () => {
          return {}
        },
      })
      .then((res: any) => {
        list.payList = res.data
      })
  }
  function doRefresh() {
    // eslint-disable-next-line prettier/prettier
    tableLoading.value = true

    http
      .get({
        url: getFeeList,
        data: () => {
          return {}
        },
      })
      .then((res: any) => {
        tableLoading.value = false

        dataList1.value = res.data
      })
      .catch(console.log)
  }
  function doRefresh2() {
    // eslint-disable-next-line prettier/prettier
    tableLoading.value = true
    columnsUse.value = columns2
    http
      .get({
        url: getService,
        data: () => {
          return { page: pagination.page, size: pagination.pageSize }
        },
      })
      .then((res: any) => {
        tableLoading.value = false
        table.handleSuccess(res.data.list)
      })
      .catch(console.log)
  }
  const balance = ref(0)
  const newsFn = () => {
    get({
      url: news,
      data: {},
    }).then((res) => {
      if (res.code == 0) {
        balance.value = res.data.balance
      }
    })
  }
  onMounted(() => {
    doRefresh()
    payListFn()
    doRefresh2()
    getpayTypeList()
    getTypeList()
    newsFn()
  })
</script>

<style scoped lang="less">
  .banList {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    width: 100%;
    padding: 20px;
    border-radius: 5px;
    background-color: #f2f3f5;
    padding-bottom: 0;
    .box-ban {
      width: calc((100% - 40px) / 3);
      height: 63px;
      border-radius: 5px;
      background-color: #ffffff;
      margin-bottom: 20px;
      text-align: center;
      line-height: 63px;
      font-size: 16px;
      color: #3491fa;
      cursor: pointer;
    }
  }
  .tables {
    margin: 0px 0px 20px;
    border-radius: 10px;
    padding: 20px;
    background-color: var(--color-bg-2);
  }
  :deep(.bcgConfig) {
    display: none;
  }
  :deep(.bcg) {
    padding: 0px;
  }
  .box {
    display: flex;
    align-items: center;
    height: 30px;
    margin: 5px 10px 10px 0px;

    .line {
      width: 5px;
      height: 25px;
      margin-right: 10px;
      background-color: #40a1ff;
    }

    .text {
      font-size: 14px;
      line-height: 25px;
      text-align: center;
      .redText {
        font-size: 14px;
        color: #f53f3f;
        margin-left: 10px;
      }
    }
  }
</style>
